<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\CrontabNew;
use app\common\model\OrderQuery;
use Endroid\QrCode\QrCode;
use think\Config;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Hook;
use think\Session;
use think\Validate;
use think\model;
use fast\Http;
use EasyWeChat;
use EasyWeChat\Foundation\Application;



/**
 * 会员中心
 */
class Play extends Frontend
{

    protected $layout = 'default';
    protected $noNeedLogin = ['play','notify','playurl','bonus'];
    protected $noNeedRight = ['*'];
    protected $model = null;
    protected $CrontabModel;
    public $app = null;
    public function _initialize()
    {


        parent::_initialize();
        $this->model = new \app\index\model\Play;
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("shop_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('play/' . $name);
    }

    /**
     * 分红计算
     */

    public function  bonus(){
        Db::startTrans();
        try{
            $CrontabModel=new CrontabNew();
            //查询订单总利润
            $OrderProfit=$CrontabModel->OrderProfit();

            //查询提出去的利润总统计
            $MoneyTotal=$CrontabModel->MoneyTotal();

            //查询贡献值
            $ContributionTotal=$CrontabModel->ContributionTotal();
            
            //平台总的利润
            $orderTotal=$OrderProfit-$MoneyTotal;

            $moneny_user_array=Db::name('user_money_log')
                ->alias('ml')
                ->join('user u',' ml.user_id=u.id','LEFT')
                ->distinct('ml.user_id')
                ->field('ml.user_id,u.score,u.money,u.bonus')
                ->whereTime('ml.createtime', 'yesterday')
                ->select();
            if(!empty($orderTotal)){

                $money_avge=$orderTotal/$ContributionTotal;
            }else{
                $money_avge=0;
            }
            if($money_avge>0){
                /*插入日志表*/
                $bonus_log['date']=strtotime(date('Y-m-d'));
                $bonus_log['money']=$money_avge;
                $bonus_log['ordermoney']=$orderTotal;
                $bonus_log['conmoney']=$ContributionTotal;
                $bonus_log['createtime']=time();
                Db::name('bonus_log')->insert($bonus_log);
                foreach ($moneny_user_array as $key=>$val){
                    if(!empty($val['score'])){
                        $money=$money_avge*$val['score'];
                        $after=($val['bonus']+$money_avge);
                        $user_money_log['user_id']=$val['user_id'];
                        $user_money_log['money']=$money;
                        $user_money_log['before']=$val['bonus'];
                        $user_money_log['after']=$after;
                        $user_money_log['memo']='分红';
                        $user_money_log['createtime']=time();
                        $user_money_log['shoporder_id']=0;
                        $user_money_log['money_type']=4;
                        $moneny_log_id=Db::name('user_money_log')->insertGetId($user_money_log); //插入分红个人流水表
                        if($moneny_log_id>0){
                            Db::name('user')->where(['id'=>$val['user_id']])->setInc('bonus',$money);  //更新用户余额
                        }

                    }
                }

            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();

        }

    }

    /**
     *
     */
    public function index()
    {
        $requst = $this->request->request();
        $user=$this->auth->getUser()->getData();

        $playUrl='http://'.$_SERVER['SERVER_NAME'].'/index/play/playurl';
        if(isset($requst['shop_id'])&&!empty($requst['shop_id'])){
            $playUrl.='?shop_id='.$requst['shop_id'];
            $shopList=Db::name('litestore_shop')->where(['id'=>$requst['shop_id']])->find();
            $playUrl.='&shop_name='.$shopList['name'];
            $playUrl.='&user_id='.$user['id'];
            $playUrl.='&category_id='.$shopList['category_id'];

        }

        $imagePath='map/images/'.$requst['shop_id'].'.png';

        $qrCode =  new QrCode();//创建生成二维码对象
        $qrCode->setText($playUrl)
            ->setSize(150)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
            ->setBackgroundColor(array('r' =>225, 'g' => 225, 'b' => 225, 'a' => 0))
            ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG)
            ->render();

    }


    function PlayUrl(){
        return;

        $configList=Db::name('config')->where(['group'=>'wechat'])->select();
        foreach ($configList as $val){
            if($val['name']=='wechat_appid'){
                $config['app_id']=$val['value'];
            }

            if($val['name']=='wechat_secret'){
                $config['secret']=$val['value'];
            }

            if($val['name']=='wechat_token'){
                $config['token']=$val['value'];
            }


            if($val['name']=='wechat_key'){
                $config['key']=$val['value'];
            }

            if($val['name']=='wechat_mch_id'){
                $config['merchant_id']=$val['value'];
            }

            if($val['name']=='wechat_key_path'){
                $config['key_path']=$val['value'];
            }

            if($val['name']=='wechat_aes_key'){
                $config['aes_key']=$val['value'];
            }

            if($val['name']=='wechat_notify_url'){
                $config['notify_url']=$val['value'];
            }
            if($val['name']=='wechat_cert_path'){
                $config['cert_path']=$val['value'];
            }
        }



        $confing_array=array(
            // 当值为 false 时，所有的日志都不会记录
            'debug'   => false,
            'app_id'  => $config['app_id'], // AppID
            'secret'  => $config['secret'], // AppSecret
            'token'   => $config['token'], // Token
            'aes_key' => $config['aes_key'], // EncodingAESKey，安全模式下请一定要填写！！！
            'log'     => [
                'level'      => 'debug',
                'permission' => 0777,
                'file'       => ROOT_PATH . '/runtime/log/easywechat.log',
            ],
            'oauth'   => [
                'scopes'   => ['snsapi_base'],
//                'callback' => $config['oauth_callback'],
            ],
            'payment' => [
                'merchant_id' => $config['merchant_id'],
                'key'         => $config['key'],
                'cert_path'   => $config['cert_path'], // XXX: 绝对路径！！！！
//                'key_path'    =>$config['key_path'], // XXX: 绝对路径！！！！...
            ],
            'guzzle'  => [
                'timeout' => 3.0, // 超时时间（秒）
            ],
        );
        $this->app = new Application($config);


        ;
        $requst=$this->request->request();


        $data=array(
            'shop_id'=>$requst['shop_id'],
            'shop_name'=>$requst['shop_name'],
            'user_id'=>$requst['user_id'],
            'category_id'=>$requst['category_id'],
            'order_no'=>date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8)
        );



        $hostUrl='http://'.$_SERVER['SERVER_NAME'].'/index/play/playurl';
        $hostUrl.='?shop_name='.$data['shop_id'];
        $hostUrl.='&shop_name='.$data['shop_name'];
        $hostUrl.='&user_id='.$data['user_id'];
        $hostUrl.='&category_id='.$data['category_id'];

        $response =$this->app->oauth->scopes(array('snsapi_base'))->redirect($hostUrl)->send();
        var_dump($response);
        exit;
        //支付宝链接
        $alipay_url = 'https://qr.alipay.com/tsx099685ffdf96nzasre20';
        //微信支付链接
        $wechat_url = 'https://payapp.weixin.qq.com/qr/AQGXFj0KWP93Es0y3w5rYzdY?t=CwAK#wechat_pay';
        //qq支付链接
        $qq_url     = 'http://vac.qq.com/wallet/qrcode.htm?m=tenpay&a=1&u=839488083&ac=7B411D7D0588EBECADFAF6E63B7619DE1B6906DDFD7C1B9919FF8442F8A7C5C0&n=%E5%B0%8F%E5%B0%8F%E9%85%A5&f=wallet';
        //京东金融支付链接
        $jd_url     = 'https://sq.jd.com/pay/Zx1fZ4';

        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') || (isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && $_SERVER['HTTP_X_CLIENT_SCHEME'] == 'https')) ? 'https://' : 'http://';
        $url   = $http_type . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//        $url   = strstr($url, '?') ? $url . '&' : $url . '?';
        $ua    = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($ua, 'Alipay') && $alipay_url) {
            //支付宝
//            $config = array(
//                "url" => $alipay_url,
//                "new" => 0,
//            );
            $data['type']=1;
            $data['open_id']='aa';
        } elseif (strpos($ua, 'MicroMessenger') && $wechat_url) {
            //微信
//            $config = array(
//                "url"  => $wechat_url,
//                "text" => "长按二维码付款",
//                "col"  => "#44b549",
//                "new"  => 1,
//            );
            $data['open_id']='aa';
            $data['type']=2;
        } elseif (strpos($ua, 'QQ/') && $qq_url) {
            //QQ
//            $config = array(
//                "url"  => $qq_url,
//                "text" => "长按二维码付款",
//                "col"  => "#0099de",
//                "new"  => 1,
//            );
            $data['open_id']='aa';
            $data['type']=3;
        } elseif (strpos($ua, 'JDJR') && $jd_url) {
            //京东金融
//            $config = array(
//                "url"  => $jd_url,
//                "new"  => 0,
//            );
            $data['open_id']='aa';
            $data['type']=4;
        } else {
            $config=array();
            $data['type']=5;
            $data['open_id']='aa';
        }
        $httpRequest=new Http();
        if($data['type']==1){


        }elseif($data['type']==2){
//            header("Content-type: text/html; charset=utf-8");
//            $wechat_config=Db::name('config')->where(['group'=>'wechat','name'=>'wechat_appid'])->find();
//            $wechat_appid=$wechat_config['value'];
//            if(empty($wechat_appid)){
//                $wechat_appid='wxc4617fb0b64da358';
//            }
//            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wechat_appid.'&redirect_uri='.urlencode($hostUrl).'&response_type=code&scope=snsapi_base&state=wx'.'#wechat_redirect';
//            $params=array();
//            header("Location:".$url);
//            $success=$httpRequest::sendRequest($url,'','POST');
//            //print_r($success);
//            return;
        }



        $this->view->assign('list',$data);

//        session::set('name',111);
//        var_dump(session::get('name'));
       // var_dump($this->auth->getUser()->getData());
        return $this->view->fetch();
    }

    function play(){
        $request=$this->request->Post();

        $litestore_shop_id=!empty($request['shop_id'])?$request['shop_id']:0;
        $shop_name=!empty($request['shop_name'])?$request['shop_name']:'';
        $play_price=!empty($request['price'])?$request['price']:0;
        $user_id=!empty($request['user_id'])?$request['user_id']:0;
        $litestore_shopcategory_id=!empty($request['category_id'])?$request['category_id']:0;
        $openId=!empty($request['openId'])?$request['openid']:0;
        $order_no=!empty($request['order_no'])?$request['order_no']:0;


        $data=array(
            'order_no'=>$order_no,
            'litestore_shop_id'=>$litestore_shop_id,
            'shop_name'=>$shop_name,
            'play_status'=>0,
            'play_price'=>100,
            'play_time'=>time(),
//            'total_price'=>$play_price+$preferential,
            'user_id'=>$user_id,
            'open_type'=>1,
            'litestore_shopcategory_id'=>$litestore_shopcategory_id,
            'openId'=>$openId
        );

       $this->model->save($data);


       return;

    }

    public function notify(){

        $orderQuery=new OrderQuery();
        $orderArry=array(
            'order_id'=>16,
            'order_no'=>'2019030797501015',
            'money'=>20,
            'user_id'=>9
        );
        $sucess=$orderQuery->orderDispose($orderArry);
        $sucess_contribution=$orderQuery->contribution($orderArry);
//        if($sucess){
//            echo '回调成功,并支付成功';
//        }
    }
    //验证缓存openid
    private function hasOpenid($app)
    {
        if(Session::get('openid')){
            return true;
        }
        if(input("?code")){
            $user = $app->oauth->user();
            Session::set('openid',$user->id);
            return true;
        }
        return false;
    }

    //获取openid
    private function get_openid()
    {
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];     //当前页面的url
        $app = third_party($url);//这个是开放平台的配置，请用自己的配置

        if (!$this->hasOpenid($app)) {
            return $response = $app->oauth->scopes(['snsapi_base'])
                ->redirect();
        }
        $open_id = Session::get('openid');
        return $open_id;

    }

    }
